package com.onegene.pdf.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.onegene.pdf.component.config.CommonParam;
import com.onegene.pdf.component.entity.PdfRequest;
import com.onegene.pdf.component.entity.Result;
import com.onegene.pdf.entity.SampleQueryVo;
import com.onegene.pdf.entity.SampleResultVo;
import com.onegene.pdf.job.support.AbstractJob;
import com.onegene.pdf.job.support.ExportParam;
import com.onegene.pdf.job.support.MyToken;
import com.onegene.pdf.job.support.PdfDesc;
import com.onegene.pdf.mapper.SampleMapper;
import com.onegene.pdf.service.DownLoadSerivce;
import com.onegene.pdf.util.PdfUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.core.date.DatePattern.PURE_DATE_PATTERN;

/**
 * @author: laoliangliang
 * @description:
 * @create: 2020/7/21 15:29
 **/
@Slf4j
@Component
public class EverydayExport extends AbstractJob {

    @Autowired
    private SampleMapper sampleMapper;

    @Autowired
    private DownLoadSerivce downLoadSerivce;

    @Autowired
    private CommonParam commonParam;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 力源的版本1 带logo5
     * {
     * "uuids":[
     * "08c7c01fec104ec3a052666d3927f232"
     * ],
     * "token":"2bbce56a-15cf-44e8-840f-016551bbb666",
     * "update":false,
     * "tempSuffix":"20200721",
     * "force":1,
     * "type":2,
     * "logoCode": 5,
     * "version":1,
     * "all":false
     * }
     */
    @Override
    public Result run(ExportParam exportParam) {
        // 查到需要生成的PDF
        SampleQueryVo sampleQueryVo = new SampleQueryVo();
        BeanUtil.copyProperties(exportParam, sampleQueryVo);

        PdfUtil.wrapStartEndTime(sampleQueryVo);

        String token = getDefaultToken();
        sampleQueryVo.setAccessToken(token);

        // 汇总描述
        List<PdfDesc> pdfDescs = new ArrayList<>();

        // 查询需要导出数据
        List<SampleResultVo> sampleResultVos = sampleMapper.selectExportSample(sampleQueryVo);
        Map<String, List<SampleResultVo>> sampleGroupMap = sampleResultVos.stream().collect(Collectors.groupingBy(s -> s.getChannelNo() + s.getType() + s.getVersion()));
        Collection<List<SampleResultVo>> values = sampleGroupMap.values();
        for (List<SampleResultVo> sampleResultVo : values) {
            SampleResultVo sampleResult = sampleResultVo.get(0);
            PdfRequest pdfRequest = new PdfRequest();
            for (Iterator<SampleResultVo> iterator = sampleResultVo.iterator(); iterator.hasNext(); ) {
                SampleResultVo resultVo = iterator.next();
                List<String> uuids = pdfRequest.getUuids();
                if (uuids == null) {
                    uuids = new ArrayList<>();
                }
                String packageCodePass = resultVo.getPackageCodePass();
                if (!StringUtils.isEmpty(packageCodePass)) {
                    List<String> packagePassList = Arrays.asList(packageCodePass.split(","));
                    if (!packagePassList.contains(resultVo.getPackageCode())) {
                        iterator.remove();
                        continue;
                    }
                }
                uuids.add(resultVo.getUuid());
                pdfRequest.setUuids(uuids);
            }
            pdfRequest.setVersion(sampleResult.getVersion());
            pdfRequest.setLogoCode(sampleResult.getLogoCode());
            pdfRequest.setType(sampleResult.getType());
            pdfRequest.setToken(token);
            pdfRequest.setTempSuffix(sampleResult.getChannelNo());
            List<String> uuids = pdfRequest.getUuids();
            if (ObjectUtil.isEmpty(uuids)) {
                continue;
            }

            downLoadSerivce.saveToDisk(pdfRequest);

            String path = PdfUtil.getPrefixPath(commonParam, pdfRequest);
            File pathDir = new File(path);
            if (!pathDir.exists()) {
                pathDir.mkdirs();
            }
            List<String> fileList = FileUtil.listFileNames(path);
            int size = sampleResultVo.size();
            if (size > 0) {
                String dirName = size + "条-" + sampleResult.getChannelName() + DateUtil.format(sampleResult.getCheckTime(), PURE_DATE_PATTERN);
                String firstDir = sampleResult.getChannelNo() + "-" + sampleResult.getChannelName();
                String versionName = PdfUtil.getVersionName(sampleResult);
                String rootPath = commonParam.ftpPrefix + firstDir + versionName + "/" + DateUtil.format(new Date(), PURE_DATE_PATTERN);
                String outPathRoot = rootPath + "/" + dirName;
                File dir = new File(outPathRoot);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                for (String fileName : fileList) {
                    FileUtil.move(new File(path + "/" + fileName), new File(outPathRoot + "/" + fileName), true);
                }


                // 写Excel
                ExcelWriter writer = ExcelUtil.getWriter();
                Map<String, String> headerAlias = new HashMap<>();
                headerAlias.put("channelNo", "渠道编号");
                headerAlias.put("checkTime", "变更为审核中的时间");
                headerAlias.put("state", "状态");
                headerAlias.put("packageName", "套餐");
                headerAlias.put("barCode", "条码");
                writer.setHeaderAlias(headerAlias);
                writer.setOnlyAlias(true);
                writer.write(sampleResultVo, true);
                String pathname = rootPath + "/" + size + "条-" + sampleResult.getChannelName() + DateUtil.format(sampleResult.getCheckTime(), PURE_DATE_PATTERN) + ".xlsx";
                writer.flush(new File(pathname));
                log.info("目录：{}，{}生成完成，数量为：{}", outPathRoot, sampleResult.getChannelName(), size);
                PdfDesc pdfDesc = new PdfDesc();
                pdfDesc.setChannelName(sampleResult.getChannelName());
                pdfDesc.setCount(size);
                pdfDesc.setFilePathName(pathname);
                pdfDesc.setDir(firstDir + versionName);
                pdfDescs.add(pdfDesc);
            }
        }
        if (pdfDescs.size() > 0) {
            log.info("导出{}", pdfDescs.toString());
            File[] fileArr = pdfDescs.stream().map(p -> new File(p.getFilePathName())).collect(Collectors.toList()).toArray(new File[]{});
            List<String> dirs = pdfDescs.stream().map(PdfDesc::getDir).collect(Collectors.toList());
            String[] toList = commonParam.toMail.split(",");
            MailUtil.send(Arrays.asList(toList), DateUtil.formatDate(new Date()) + "验收PDF报告", "<h1>" + pdfDescs.toString() + "</h1><div>清单请查看附件，验收请到IT服务部专用机查看</div><div>查看目录：" + JSON.toJSONString(dirs) + "</div>", true, fileArr);
        } else {
            log.info("今日没有每日渠道数据PDF");
        }
        return Result.ok(pdfDescs);
    }

    private String getDefaultToken() {
        Environment environment = applicationContext.getEnvironment();
        String profile = environment.getActiveProfiles()[0];
        String url;
        if ("dev".equals(profile)) {
            url = "http://infoapi.dev.1genehealth.com/infowork-auth/oauth/token?username=whoisyoudad&password=123456&grant_type=password";
        } else {
            url = "http://infoapi.1genehealth.com/infowork-auth/oauth/token?username=whoisyoudad&password=123456&grant_type=password";
        }
        HttpRequest httpRequest = HttpUtil.createPost(url).basicAuth("client", "secret");
        HttpResponse execute = httpRequest.execute();
        String body = execute.body();
        MyToken token = JSON.parseObject(body, MyToken.class);
        return token.getAccessToken();
    }


}
